package com.lst.api.utils;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.lst.tools.basics.utils.DateUtils;
import com.lst.tools.mybatis.entity.BaseModel;
import com.lst.tools.mybatis.entity.DeleteBaseModel;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Frank
 * @date: 2019/9/24 16:13
 * @version: V1.0
 */
public class MysqlGeneratorUtils {

    public static void main(String[] args) {
        generator("Frank",
                "lst_order",
                "lst_order_item_product",
                "lst_order_follow",
                "lst_order_contract",
                "lst_loan_type");
    }

    public static void generator(String author, String... tableNames) {
        AutoGenerator autoGenerator = new AutoGenerator();
        /**************************配置 GlobalConfig************************************/
        GlobalConfig globalConfig = new GlobalConfig();
        //作者
        globalConfig.setAuthor(author);
        globalConfig.setDateType(DateType.ONLY_DATE);
        // 是否打开输出目录
        globalConfig.setOpen(false);
        globalConfig.setSwagger2(true);
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        globalConfig.setServiceImplName("%sService");
        autoGenerator.setGlobalConfig(globalConfig);

        /**************************数据源配置************************************/
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://47.98.104.252:3306/lst?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("Root@3306");
        // 自定义数据库表字段类型转换【可选】
        dataSourceConfig.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                System.out.println("转换类型：" + fieldType);
                //tinyint转换成Boolean
                if (fieldType.toLowerCase().contains("tinyint")) {
                    return DbColumnType.INTEGER;
                }
                //将数据库中datetime转换成date
                if (fieldType.toLowerCase().contains("datetime")) {
                    return DbColumnType.DATE;
                }
                //将数据库中datetime转换成date
                if (fieldType.toLowerCase().contains("decimal")) {
                    return DbColumnType.DOUBLE;
                }
                return super.processTypeConvert(globalConfig, fieldType);
            }
        });
        autoGenerator.setDataSource(dataSourceConfig);

        /**************************自定义代码模板************************************/
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setEntity("templates/entity2.java");
        templateConfig.setMapper("templates/mapper2.java");
        templateConfig.setXml("templates/mapperXml2.java");
        templateConfig.setService("templates/service2.java");
        templateConfig.setServiceImpl("templates/serviceImpl2.java");
        templateConfig.setController("templates/controller2.java");
        autoGenerator.setTemplate(templateConfig);

        /**************************配置自定义属性注入.vm模板中，通过${cfg.abc}获取属性************************************/
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_FORMAT_2));
                this.setMap(map);
            }
        };
        autoGenerator.setCfg(injectionConfig);

        /**************************包配置************************************/
        String userDir = System.getProperty("user.dir");
        String javaPath = userDir + "/lst-api/src/main/java";
        String resourcesPath = userDir + "/lst-api/src/main/resources";
        Map<String, String> pathInfo = new HashMap<>(6);
        pathInfo.put(ConstVal.ENTITY_PATH, javaPath + "/com/lst/api/entity");
        pathInfo.put(ConstVal.MAPPER_PATH, javaPath + "/com/lst/api/mapper");
        pathInfo.put(ConstVal.XML_PATH, resourcesPath + "/mapper");
        pathInfo.put(ConstVal.SERVICE_PATH, javaPath + "/com/lst/api/service");
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH, javaPath + "/com/lst/api/service/impl");
        pathInfo.put(ConstVal.CONTROLLER_PATH, javaPath + "/com/lst/api/controller/basic");
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setPathInfo(pathInfo);

        packageConfig.setParent("com.lst.api")
                .setEntity("entity")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl")
                .setController("controller.basic");
        autoGenerator.setPackageInfo(packageConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 使用lombok
        strategy.setSuperEntityColumns(BaseModel.ID, BaseModel.CREATE_AT, BaseModel.UPDATE_AT, DeleteBaseModel.IS_DELETE);
        strategy.setEntityLombokModel(true);
        strategy.setInclude(tableNames);
        strategy.setSuperEntityClass(BaseModel.class);
        strategy.setRestControllerStyle(true);
        strategy.setTablePrefix("lst_");
        autoGenerator.setStrategy(strategy);
        autoGenerator.execute();
    }
}
